#!/usr/bin/env python3
"""
DirectoryScanner 目录扫描器
递归扫描指定目录下的所有子目录，识别 Git 仓库
"""

import os
from typing import List, Optional
from pathlib import Path
from models.git_repository import GitRepository


class DirectoryScanner:
    """目录扫描器"""
    
    def __init__(self, max_depth: int = 10):
        """
        初始化目录扫描器
        
        Args:
            max_depth: 最大扫描深度
        """
        self.max_depth = max_depth
    
    def find_git_repositories(self, 
                           root_directory: str, 
                           include_patterns: Optional[List[str]] = None,
                           exclude_patterns: Optional[List[str]] = None) -> List[str]:
        """
        查找所有 Git 仓库
        
        Args:
            root_directory: 根目录路径
            include_patterns: 包含模式列表
            exclude_patterns: 排除模式列表
            
        Returns:
            List[str]: Git 仓库路径列表
        """
        git_repos = []
        
        if not os.path.exists(root_directory) or not os.path.isdir(root_directory):
            return git_repos
        
        try:
            # 遍历目录
            for root, dirs, files in os.walk(root_directory, topdown=True):
                # 限制扫描深度
                current_depth = len(Path(root).relative_to(Path(root_directory)).parts)
                if current_depth > self.max_depth:
                    continue
                
                # 检查当前目录是否为 Git 仓库
                if self._is_git_repo(root):
                    git_repos.append(root)
                
                # 检查子目录
                for dir_name in dirs:
                    dir_path = os.path.join(root, dir_name)
                    if self._is_git_repo(dir_path):
                        git_repos.append(dir_path)
                        
        except Exception as e:
            print(f"扫描目录时发生错误: {str(e)}")
        
        return git_repos
    
    def _is_git_repo(self, path: str) -> bool:
        """
        检查路径是否为 Git 仓库
        
        Args:
            path: 路径
            
        Returns:
            bool: 是否为 Git 仓库
        """
        try:
            git_dir = os.path.join(path, '.git')
            return os.path.exists(git_dir) and os.path.isdir(git_dir)
        except Exception:
            return False
    
    def is_valid_git_repo(self, path: str) -> bool:
        """
        验证 Git 仓库的有效性
        
        Args:
            path: 仓库路径
            
        Returns:
            bool: 是否为有效的 Git 仓库
        """
        try:
            # 创建 GitRepository 对象进行验证
            repo = GitRepository(path)
            return repo.is_valid
        except Exception:
            return False
    
    def scan_directory_structure(self, root_directory: str) -> dict:
        """
        扫描目录结构
        
        Args:
            root_directory: 根目录路径
            
        Returns:
            dict: 目录结构信息
        """
        structure = {
            "root": root_directory,
            "directories": [],
            "git_repos": [],
            "total_files": 0,
            "total_dirs": 0
        }
        
        try:
            for root, dirs, files in os.walk(root_directory):
                # 统计文件和目录
                structure["total_files"] += len(files)
                structure["total_dirs"] += len(dirs)
                
                # 记录目录
                relative_path = os.path.relpath(root, root_directory)
                if relative_path == ".":
                    relative_path = "root"
                structure["directories"].append(relative_path)
                
                # 检查 Git 仓库
                if self._is_git_repo(root):
                    structure["git_repos"].append(relative_path)
                    
        except Exception as e:
            structure["error"] = str(e)
        
        return structure


def test_directory_scanner():
    """测试 DirectoryScanner"""
    print("测试 DirectoryScanner...")
    
    scanner = DirectoryScanner(max_depth=5)
    
    # 扫描当前目录
    git_repos = scanner.find_git_repositories(".", ["*"], ["*test*", "*temp*"])
    print(f"找到 {len(git_repos)} 个 Git 仓库:")
    for repo in git_repos:
        print(f"  - {repo}")
    
    # 验证仓库有效性
    for repo in git_repos[:3]:  # 只测试前3个
        is_valid = scanner.is_valid_git_repo(repo)
        print(f"仓库 {repo} 是否有效: {is_valid}")
    
    # 扫描目录结构
    structure = scanner.scan_directory_structure(".")
    print(f"目录结构: {structure}")


if __name__ == "__main__":
    test_directory_scanner()